import { PrismaClient, Prisma } from '../../prisma/client/index.js'
import { config } from '@/config/env'
export { PrismaClient, Prisma }
// 扩展 Prisma 客户端类型
declare global {
  var __prisma: PrismaClient | undefined
}

// 创建 Prisma 客户端实例
const createPrismaClient = () => {
  return new PrismaClient({
    log: config.isDevelopment
      ? ['query', 'info', 'warn', 'error']
      : ['warn', 'error'],
    datasources: {
      db: {
        url: config.database.url,
      },
    },
  })
}

// 单例模式，避免在开发环境中创建多个连接
const prisma = globalThis.__prisma ?? createPrismaClient()

if (config.isDevelopment) {
  globalThis.__prisma = prisma
}

// 数据库连接健康检查
export const checkDatabaseConnection = async (): Promise<boolean> => {
  try {
    await prisma.$queryRaw`SELECT 1`
    return true
  } catch (error) {
    console.error('Database connection failed:', error)
    return false
  }
}

// 优雅关闭数据库连接
export const closeDatabaseConnection = async (): Promise<void> => {
  try {
    await prisma.$disconnect()
    console.log('Database connection closed')
  } catch (error) {
    console.error('Error closing database connection:', error)
  }
}

// 数据库事务辅助函数
export const withTransaction = async <T>(
  callback: (tx: Omit<PrismaClient, '$connect' | '$disconnect' | '$on' | '$transaction' | '$use' | '$extends'>) => Promise<T>
): Promise<T> => {
  return await prisma.$transaction(callback)
}

// 导出 Prisma 客户端
export { prisma }
export default prisma

// 进程退出时关闭数据库连接
process.on('beforeExit', async () => {
  await closeDatabaseConnection()
})

process.on('SIGINT', async () => {
  await closeDatabaseConnection()
  process.exit(0)
})

process.on('SIGTERM', async () => {
  await closeDatabaseConnection()
  process.exit(0)
})
